/*
 * @Author: Sam
 * @Date: 2020-10-12 15:23:33
 * @LastEditTime: 2021-07-21 10:51:45
 * @LastEditors: Sam
 * @Description: 
 * @FilePath: \resourcesf:\thework\tofba-client\src\permission.js
 * @可以输入预定的版权声明、个性签名、空行等
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// 判断页面刷新,
if (performance.navigation.type == 1) {
  store.dispatch('user/clearRoles')
}
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // 跳转页面隐藏dialog
  store.dispatch('app/toggleDialog', false)
  // 开始进度条
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已经登录
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // 注意：角色必须是对象数组！ 例如：['admin']或，['developer'，'editor']
          const { roles } = await store.dispatch('user/getInfo')
          // 根据角色生成可访问的路线图
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          //  动态添加可访问的路线
          router.addRoutes(accessRoutes)
          // hack方法，以确保addRoutes是完整的
          // 设置replace：true，因此导航不会留下历史记录
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (to.query.websiteToken) {
      store
        .dispatch('user/login2', { websiteToken: to.query.websiteToken })
        .then(() => {
          this.$router.push({ path: '/' })
          this.$store.dispatch('user/getInfo')
          this.$store.dispatch('public/getPublicData')
        })
        .catch(err => {

        })
      next()
    }

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
